<template>
  <div id="app">
    <li>
      <label>
        <input type="checkbox" :checked="todos.done" @change="handleCheck(todos.id)"/>
        <span v-show="!todos.isEdit">{{todos.name}}</span>
        <input 
        v-show="todos.isEdit"
        type="text"
        :value="todos.name"
        ref="inputTitle"
        @blur="handleBlur(todos,$event)"
        >
      </label>
      <button class="btn btn-danger" @click="handleDelete(todos.id)">删除</button>
      <button class="btn btn-edit" @click="handleEdit(todos)" v-show="!todos.isEdit">编辑</button>
    </li>
  </div>
</template>
<script>
export default {
  name: "MyItem",
  props:['todos'],
  methods:{
    handleCheck(id){
      // this.changeTodo(id)
      this.$bus.$emit('changeTodo',id)
    },
    //删除一个todos
    handleDelete(id){
      //需要app来进行删除
      if(confirm("确定")){
        // this.deleteTodos(id)
        this.$bus.$emit('deleteTodos',id)
      }
    },
    //编辑一个todos
    handleEdit(todos){
      //如果todos有isEdit的属性的话，那么就直接为true,这样就能出现input框
      if(Object.hasOwnProperty.call(todos,'isEdit')){
        todos.isEdit = true;
      }else{
         this.$set(todos,'isEdit',true); //正确的往todos中添加一个属性
      }
      //当ifelse执行完成后，dom重新渲染了，再执行下面的代码，而不是等到方法里所有的语句执行完成了后重新渲染dom
      this.$nextTick(function(){
        this.$refs.inputTitle.focus();
      })
    },
    //失去焦点后todos的isEdit属性变成false
    handleBlur(todos,e){
      todos.isEdit = false;
      //失去焦点触发回调，传递更改数据
      this.$bus.$emit('updateTodos',todos.id,e.target.value)
    }
  }
};
</script>
<style scoped>
/*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}
/* 移动到对应的列后，背景色变为灰色 */
li:hover{
  background:#ddd;
}
/* 悬浮的时候出现button */
li:hover button{
  display:block;
}
</style>
